package com.sky.controller.Appointment;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.entity.SysDictData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/appointment")
public class AppointmentController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    // 正则表达式：匹配数字后面的 L 后缀（如 124L、0L）
    private static final Pattern LONG_SUFFIX_PATTERN = Pattern.compile("(\\d+)L");

    @GetMapping("/list")
    public List<SysDictData> list() {
        try {
            String key = "sys_dict:cart_services_type";
            // 1. 读取原始非标准 JSON 字符串
            String rawJson = stringRedisTemplate.opsForValue().get(key);
            if (rawJson == null || rawJson.isEmpty()) {
                return List.of();
            }
            System.out.println("原始非标准 JSON：" + rawJson);

            // 2. 清洗：去掉所有数字后面的 L 后缀（转为标准 JSON 数字）
            String standardJson = cleanLongSuffix(rawJson);
            System.out.println("清洗后的标准 JSON：" + standardJson);

            // 3. 用 Jackson 解析标准 JSON
            List<SysDictData> dataList = objectMapper.readValue(
                    standardJson,
                    new TypeReference<List<SysDictData>>() {}
            );

            return dataList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析字典数据失败：" + e.getMessage());
        }
    }

    /**
     * 清洗 JSON 字符串中的 Long 后缀 L
     * 例如："dictCode":124L → "dictCode":124
     */
    private String cleanLongSuffix(String json) {
        Matcher matcher = LONG_SUFFIX_PATTERN.matcher(json);
        // 替换所有匹配的 "数字L" 为 "数字"
        return matcher.replaceAll("$1");
    }
}
